package com.qcorm.core;


import org.apache.log4j.Logger;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * ResultSet映射到实体
 */
public class RsMapper {

    static Logger logger = Logger.getLogger(BaseDao.class.getName());

    private RsMapper(){}

    /**
     *
     * @param clazz
     * @param rs
     * @param <T>
     * @return
     */
    public static <T> List<T> rsMapToEntityList(Class<T> clazz, ResultSet rs) {
        ResultSetMetaData rsmd = null;
        List<T> list = new ArrayList<T>();
        Method[] methods = clazz.getMethods();
        try {
            rsmd = rs.getMetaData();
            while (rs.next()) {
                T t = clazz.newInstance();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    String temp = rsmd.getColumnName(i);
                    Field field=clazz.getDeclaredField(temp);

                    Method method = getMethod(methods, temp, 0);
                    if(method == null){
                        logger.error("rsMapToEntityList getMethod未获取到内容");
                        return list;
                    }
                    if(field.getType().equals(String.class)){
                        method.invoke(t, rs.getString(temp));
                    }else if(field.getType().equals(int.class)){
                        method.invoke(t, rs.getInt(temp));
                    }else if(field.getType().equals(short.class)){
                        method.invoke(t, rs.getShort(temp));
                    }else if(field.getType().equals(long.class)){
                        method.invoke(t, rs.getLong(temp));
                    }else if(field.getType().equals(Date.class)){
                        method.invoke(t, rs.getDate(temp));
                    }else{
                    	throw new Exception("Not Support filed type!");
                    }
                }
                list.add(t);
            }
        } catch (Exception e) {
            logger.error("rsMapToEntityList exception",e);
        }
        return list;
    }


    /**
     *
     * @param methods
     * @param columName
     * @param type 0获取set方法，1获取get方法
     * @return
     */
    public static Method getMethod(Method[] methods , String columName, int type) {
    	String methodName = null;
    	if(type ==0){
    		methodName="set"+columName;
    	}else if(type ==1){
    		methodName="get"+columName;
    	}else{
    		new Exception("type不合法");
    	}
        for(Method method : methods){
        	if(method.getName().equalsIgnoreCase(methodName))
        	{
        		return method;
        	}
        }
        return null;
    }
}
